var app = angular.module('BaseControl');

app.directive("datagrid", ['$compile', 'PublicEnum', 'PublicFunction', function($compile, PublicEnum, PublicFunction) {
    return {
        restrict: "E",
        scope: {
            module: '=',
            rowdblclick: '&',       //双击表格行后
            rowchange: '&',         //行改变后
            cellvaluechange: '&',   //单元格值发生变化后
            cellclick: '&',     //点击单元格前
            addrow: '&',        //新增行后
            deleterow: '&',     //删除行后
            order: '&'          //排序完成后
        },
        templateUrl: 		// 替换HTML (使用scope中的变量)
            'modules/Base/client/views/templates/DataGrid.html',
        replace: true,			// 使用模板替换原始标记
        transclude: true,		// 不复制原始HTML内容
        controller: ['$scope', function ($scope) {
            var ctrl = this;
            ctrl.scope = $scope;

            $scope.Columns = [];
            $scope.Checked = {IsCheckedAll : false};      //左上角全选按钮绑定值，这里必须是对象的属性，因为CheckBox控件的value的值绑定问题
            $scope.CheckColumn = {Width: '50px'};     //定义CheckBox列的宽度以及
            $scope.Edit = {
                IsEdit : true,
                IsAdd : true,
                IsModify : true,
                IsDelete : true
            };

            var getRecordById = function(id){
                for(var i=0; i<$scope.module.Records.length; i++){
                    if($scope.module.Records[i]._id == id){
                        return $scope.module.Records[i];
                    }
                }
                return null;
            };
            var getRowIndexById = function(id){
                for(var i=0; i<$scope.Dom._BodyElement.rows.length; i++){
                    if($scope.Dom._BodyElement.rows[i].getAttribute('key') == id){
                        return i;
                    }
                }
                return -1;
            };
            $scope.btnAdd = function(){
                var newRecord = $scope.module.add();
                $scope.addRowHtml(newRecord);
                $scope.Dom._BodyElement.rows[$scope.Dom._BodyElement.rows.length - 1].click();
                $scope.$parent.$digest();

                $scope.addrow();
            };
            $scope.batchEdit = function(){
                alert("批量编辑");
            };

            //全选\取消全选
            $scope.checkedAllClick = function(){
                for(var i=0; i<$scope.Dom._BodyLeftElement.rows.length; i++) {
                    getRecordById($scope.Dom._BodyLeftElement.rows[i].getAttribute('key')).IsSelected = event.srcElement.checked;
                    $scope.Dom._BodyLeftElement.rows[i].cells[0].children[0].children[0].checked = event.srcElement.checked
                }
            };
            //行选择\取消选择
            $scope.checkedLineClick = function() {
                $scope.module.FocusedRecord.IsSelected = event.srcElement.checked;

                if($scope.module.FocusedRecord.IsSelected){
                    var isAllSelected = true;
                    for (var i = 0; i < $scope.Dom._BodyElement.rows.length; i++) {
                        if (!getRecordById($scope.Dom._BodyLeftElement.rows[i].getAttribute('key')).IsSelected) {
                            isAllSelected = false;
                            break;
                        }
                    }
                    if ($scope.Checked.IsCheckedAll != isAllSelected) {
                        $scope.Checked.IsCheckedAll = isAllSelected;
                        $scope.$digest();
                    }
                }
                else{
                    if ($scope.Checked.IsCheckedAll != isAllSelected) {
                        $scope.Checked.IsCheckedAll = false;
                        $scope.$digest();
                    }
                }
            };

            $scope.rowClick = function() {
                $scope.$apply(function(){
                    var domRow = event.srcElement;
                    while (domRow.tagName.toLowerCase() != "tr") {
                        domRow = domRow.parentNode;
                    }
                    var currentLineID = domRow.getAttribute('key');

                    //如果不是行触发，而是行的子元素触发的，则不用处理，比如：日历控件里面就带有tr元素
                    if(currentLineID == null){
                        return;
                    }

                    //校验是否是子Grid触发，因为参照控件弹出的Grid是在主Grid的TD中，也会触发主Grid的RowClick事件
                    var gridElement = domRow.parentNode.parentNode.parentNode.parentNode.parentNode;
                    while(gridElement.tagName.toLowerCase() != 'div' || gridElement.getAttribute('class') == null || 
                        gridElement.getAttribute('class').toLowerCase() != 'datagriddiv'){
                        gridElement = gridElement.parentNode;
                    }
                    if(gridElement != $scope.Dom._tableDiv){
                        return;
                    }

                    if($scope.module.FocusedRecord == null || $scope.module.FocusedRecord._id != currentLineID) {
                        if($scope.module.FocusedRecord != null){
                            var oldRowIndex = getRowIndexById($scope.module.FocusedRecord._id);

                            if($scope.IsSelect) {
                                $scope.Dom._BodyLeftElement.rows[oldRowIndex].removeAttribute('style');
                            }
                            $scope.Dom._BodyElement.rows[oldRowIndex].removeAttribute('style');
                            if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)) {
                                $scope.Dom._BodyRightElement.rows[oldRowIndex].removeAttribute('style');
                            }
                        }

                        $scope.module.FocusedRecord = getRecordById(currentLineID);
                        if($scope.IsSelect) {
                            $scope.Dom._BodyLeftElement.rows[domRow.rowIndex].style.backgroundColor = '#FAEBB2';
                        }
                        $scope.Dom._BodyElement.rows[domRow.rowIndex].style.backgroundColor = '#FAEBB2';
                        if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)) {
                            $scope.Dom._BodyRightElement.rows[domRow.rowIndex].style.backgroundColor = '#FAEBB2';
                        }
                        $scope.rowchange();
                    }
                });
            };
            $scope.cellClick = function(){
                if($scope.Edit.IsEdit && $scope.Edit.IsModify) {
                    var srcElem = event.srcElement;
                    while(srcElem){
                        if(srcElem.tagName.toLowerCase() == 'td'){
                            break;
                        }
                        else{
                            srcElem = srcElem.parentNode;
                        }
                    }
                    srcElem = srcElem.children[0];

                    if (srcElem.tagName.toLowerCase() == "div") {
                        var column = $scope.Columns[srcElem.parentNode.cellIndex];
                        $scope.cellclick({columnName: column.scope.ValueField});
                        if (column.scope.IsEdit) {
                            var record = $scope.module.FocusedRecord;
                            if(column.scope.ValueField.indexOf(".") > -1){
                                var fields = column.scope.ValueField.split(".");
                                var strEvalField = "record";
                                //补齐父对象，不然会报父对象undefined
                                for(var i=0; i<fields.length - 1; i++){
                                    strEvalField += "." + fields[i];
                                    var parentObj = eval(strEvalField);
                                    if(parentObj == undefined || parentObj == null){
                                        eval(strEvalField + " = {};");
                                    }
                                }
                            }

                            column.scope.value = eval("record." + column.scope.ValueField);
                            srcElem.style.display = 'none';
                            var inputBox;

                            if(column.scope.ControlType == PublicEnum.ControlType.Calendar){
                                window.setTimeout(function () {
                                    inputBox = column.Element.children[0];
                                    srcElem.parentNode.appendChild(inputBox);

                                    window.setTimeout(function () {
                                        inputBox.children[0].focus();
                                    }, 1);
                                }, 1);
                            }
                            else if(column.scope.ControlType == PublicEnum.ControlType.Refer){
                                column.scope.key = eval("record." + column.scope.KeyField);
                                column.scope.text = eval("record." + column.scope.TextField);

                                inputBox = column.Element.children[0];
                                column.scope.Element = inputBox;        //因为参照列获取不到参照控件
                                srcElem.parentNode.appendChild(inputBox);
                                window.setTimeout(function () {
                                    inputBox.children[0].children[0].focus();
                                }, 100);
                            }
                            else {
                                inputBox = column.Element.children[0];
                                srcElem.parentNode.appendChild(inputBox);
                                window.setTimeout(function () {
                                    inputBox.focus();
                                }, 1);
                            }
                            column.scope.$digest();
                        }
                    }
                }
            };
            $scope.keyDown = function(){
                var tdElement = event.srcElement;
                while(tdElement){
                    if(tdElement.tagName.toLowerCase() == 'td'){
                        break;
                    }
                    tdElement = tdElement.parentNode;
                }
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40){
                    var cellIndex = tdElement.cellIndex;
                    var rowIndex = tdElement.parentNode.rowIndex;
                    var replyDiv = null;
                    if(event.keyCode == 13) {
                        var isFindNextEditColumn = false;
                        if (cellIndex < $scope.Dom._BodyElement.rows[rowIndex].cells.length - 1) {
                            for (var i = cellIndex + 1; i < $scope.Dom._BodyElement.rows[rowIndex].cells.length; i++) {
                                if ($scope.Columns[i].scope.IsEdit && $scope.Columns[i].scope.IsDisplay) {
                                    isFindNextEditColumn = true;
                                    replyDiv = $scope.Dom._BodyElement.rows[rowIndex].cells[i].children[0];
                                    break;
                                }
                            }
                        }
                        if (!isFindNextEditColumn) {
                            if (rowIndex < $scope.Dom._BodyElement.rows.length - 1) {
                                for (var i = 0; i < $scope.Dom._BodyElement.rows[rowIndex + 1].cells.length; i++) {
                                    if ($scope.Columns[i].scope.IsEdit && $scope.Columns[i].scope.IsDisplay) {
                                        replyDiv = $scope.Dom._BodyElement.rows[rowIndex + 1].cells[i].children[0];
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else if(event.keyCode == 38) {
                        if(rowIndex > 0){
                            if ($scope.Columns[cellIndex].scope.IsEdit && $scope.Columns[cellIndex].scope.IsDisplay) {
                                replyDiv = $scope.Dom._BodyElement.rows[rowIndex - 1].cells[cellIndex].children[0];

                                //$scope.Dom._tableDiv.scrollTop = $scope.Dom._tableDiv.scrollTop - 36;
                            }
                        }
                    }
                    else if(event.keyCode == 40) {
                        if(rowIndex < $scope.Dom._BodyElement.rows.length - 1){
                            if ($scope.Columns[cellIndex].scope.IsEdit && $scope.Columns[cellIndex].scope.IsDisplay) {
                                replyDiv = $scope.Dom._BodyElement.rows[rowIndex + 1].cells[cellIndex].children[0];

                                //$scope.Dom._tableDiv.scrollTop = $scope.Dom._tableDiv.scrollTop + 36;
                            }
                        }
                    }

                    if(replyDiv != null){
                        event.srcElement.blur();

                        //滚动条位置处理开始
                        var scrollYwidth = $scope.Dom._tableDiv.offsetWidth - $scope.Dom._tableDiv.clientWidth - 2;     //垂直滚动条的宽度
                        var scrollXwidth = $scope.Dom._tableDiv.offsetHeight - $scope.Dom._tableDiv.clientHeight - 2;   //水平滚动条的宽度
                        if(replyDiv.getBoundingClientRect().bottom > $scope.Dom._tableDiv.getBoundingClientRect().bottom - scrollXwidth){
                            $scope.Dom._tableDiv.scrollTop += replyDiv.getBoundingClientRect().bottom - ($scope.Dom._tableDiv.getBoundingClientRect().bottom - scrollXwidth) + 4;
                        }
                        else if(replyDiv.getBoundingClientRect().top < $scope.Dom._HeadElement.getBoundingClientRect().bottom){
                            $scope.Dom._tableDiv.scrollTop -= $scope.Dom._HeadElement.getBoundingClientRect().bottom - replyDiv.getBoundingClientRect().top + 2;
                        }

                        if(replyDiv.getBoundingClientRect().right > $scope.Dom._tableDiv.getBoundingClientRect().right - scrollYwidth){
                            $scope.Dom._tableDiv.scrollLeft += replyDiv.getBoundingClientRect().right - ($scope.Dom._tableDiv.getBoundingClientRect().right - scrollYwidth) + 3;
                        }
                        else if(replyDiv.getBoundingClientRect().left < $scope.Dom._BodyLeftElement.getBoundingClientRect().right){
                            $scope.Dom._tableDiv.scrollLeft -= $scope.Dom._BodyLeftElement.getBoundingClientRect().right - replyDiv.getBoundingClientRect().left + 3;
                        }
                        //滚动条位置处理结束
                        replyDiv.click();
                    }
                }
            };

            $scope.addRow = function(){
                var newRecord;
                var rowIndex;
                if($scope.module.FocusedRecord != null) {
                    var focusedRecordIndex = $scope.module.getRecordIndex($scope.module.FocusedRecord);
                    for(var i=0; i< $scope.Dom._BodyElement.rows.length; i++){
                        if($scope.Dom._BodyElement.rows[i].getAttribute('key') == $scope.module.FocusedRecord._id){
                            rowIndex = i;
                            break;
                        }
                    }
                    if(focusedRecordIndex == $scope.module.Records.length - 1){
                        newRecord = $scope.module.add();
                    }
                    else {
                        newRecord = $scope.module.add(focusedRecordIndex + 1);
                    }
                    $scope.$parent.$digest();

                    if(rowIndex == $scope.module.PageSize - 1){
                        $scope.module.nextPage();
                        $scope.Dom._BodyElement.rows[0].click();
                    }
                    else{
                        $scope.addRowHtml(newRecord, rowIndex + 1);
                        $scope.Dom._BodyElement.rows[rowIndex + 1].click();

                        if($scope.Dom._BodyElement.rows.length > $scope.module.PageSize){
                            $scope.deleteRowHtml($scope.Dom._BodyElement.rows.length - 1);
                        }
                    }
                }
                else{
                    newRecord = $scope.module.add();                    

                    if($scope.Dom._BodyElement.rows.length == $scope.module.PageSize - 1){
                        $scope.module.nextPage();
                        $scope.Dom._BodyElement.rows[0].click();
                    }
                    else{
                        $scope.addRowHtml(newRecord);
                        $scope.Dom._BodyElement.rows[$scope.Dom._BodyElement.rows.length - 1].click();
                    }
                } 
                $scope.addrow();
            };
            //删除记录以及对应的行
            var rowDelete = function(record){
                var focusedRecordIndex = $scope.module.getRecordIndex(record);
                var rowIndex = getRowIndexById(record._id);
                var pageCount = $scope.module.PageCount;  //必须先记录，删除行有可能改变页数

                $scope.module.deleteRecord(record);

                if(rowIndex >= 0){
                    $scope.deleteRowHtml(rowIndex);
                    if($scope.module.PageNum < pageCount - 1){
                        var lastRecord = $scope.module.findRecordById($scope.Dom._BodyElement.rows[$scope.Dom._BodyElement.rows.length - 1].getAttribute('key'));
                        var lastRecordIndex = $scope.module.getRecordIndex(lastRecord);
                        $scope.addRowHtml($scope.module.Records[lastRecordIndex + 1]);
                    }

                    if($scope.Dom._BodyElement.rows.length - 1 >= rowIndex){
                        $scope.Dom._BodyElement.rows[rowIndex].click();
                    }
                    else if($scope.Dom._BodyElement.rows.length > 0){
                        $scope.Dom._BodyElement.rows[rowIndex - 1].click();
                    }
                    else{
                        if($scope.module.PageNum > 1){
                            $scope.module.prePage();
                            $scope.Dom._BodyElement.rows[0].click();
                        }
                    }
                }
            };
            $scope.deleteRow = function(){
                var focusedRecord = $scope.module.FocusedRecord;
                rowDelete($scope.module.FocusedRecord);
                $scope.$parent.$digest();
                $scope.deleterow({record: focusedRecord});
            };
            $scope.batchDelete = function(){
                var records = $scope.module.getSelectRecords();
                for(var i=0; i<records.length; i++){
                    rowDelete(records[i]);
                };
            };
            $scope.addColumn = function(columnScope, element){
                var column = {
                    scope: columnScope,
                    Element: element
                };
                $scope.Columns.push(column);
            };
            $scope.addRowHtml = function(record, rowIndex){
                //创建checkbox列
                if($scope.IsSelect){
                    var newBodyLeftRow;
                    if(rowIndex != undefined && rowIndex >=0){
                        newBodyLeftRow = $scope.Dom._BodyLeftElement.insertRow(rowIndex);
                    }
                    else{
                        newBodyLeftRow = $scope.Dom._BodyLeftElement.insertRow();
                    }

                    if(this.FocusedRecord != null && record._id == this.FocusedRecord._id){
                        newBodyLeftRow.style.backgroundColor = '#FAEBB2';
                    }
                    newBodyLeftRow.setAttribute('key', record._id);
                    newBodyLeftRow.addEventListener('click', function(){ $scope.rowClick(); }, true);
                    newBodyLeftRow.addEventListener('dblclick', function(){ $scope.rowdblclick(); }, false);
                    var newBodyLeftRowCell = newBodyLeftRow.insertCell();

                    newBodyLeftRowCell.innerHTML =
                        '<div style="width:' + $scope.CheckColumn.Width + ';">' +
                            '<input type="checkbox" class="CheckBox"/>';

                    newBodyLeftRowCell.children[0].children[0].addEventListener('click', function(){ $scope.checkedLineClick(); }, false);
                    newBodyLeftRowCell.children[0].children[0].addEventListener('keydown', function(){
                        if(event.keyCode == 32) {
                            $scope.checkedLineClick();
                            event.preventDefault();
                        }
                    }, false);
                }

                //创建表体区域
                var newBodyRow;
                if(rowIndex != undefined && rowIndex >=0){
                    newBodyRow = $scope.Dom._BodyElement.insertRow(rowIndex);
                }
                else{
                    newBodyRow = $scope.Dom._BodyElement.insertRow();
                }

                if(this.FocusedRecord != null && record._id == this.FocusedRecord._id){
                    newBodyRow.style.backgroundColor = '#FAEBB2';
                }
                newBodyRow.setAttribute('key', record._id);
                newBodyRow.addEventListener('click', function(){ $scope.rowClick(); }, true);
                newBodyRow.addEventListener('dblclick', function(){ $scope.rowdblclick(); }, false);
                for (var i = 0; i < $scope.Columns.length; i++){
                    var column = $scope.Columns[i];
                    var newBodyRowCell = newBodyRow.insertCell();
                    var cellValue;
                    if(column.scope.ValueField.indexOf(".") > -1){
                        var fields = column.scope.ValueField.split(".");
                        var strEvalField = "record";
                        for(var j=0; j<fields.length; j++){
                            strEvalField += "." + fields[j];
                            cellValue = eval(strEvalField);
                            if(j < fields.length - 1){
                                if(cellValue == undefined || cellValue == null || cellValue.constructor != Object){
                                    eval(strEvalField + " = {}");
                                }
                            }
                        }
                    }
                    else{
                        cellValue = record[column.scope.ValueField];
                    }
                    if(column.scope.ControlType == PublicEnum.ControlType.TextBox){
                        if(cellValue == undefined || cellValue == null || cellValue == ''){
                            cellValue = '&nbsp;';
                        }
                    }
                    else if(column.scope.ControlType == PublicEnum.ControlType.NumberBox){
                        if(column.scope.Round != null) {
                            cellValue = column.scope.Round.formatNumber(cellValue);
                        }
                        else{
                            if(cellValue == undefined || cellValue == null){
                                cellValue = '';
                            }
                        }
                    }
                    else if(column.scope.ControlType == PublicEnum.ControlType.PercentBox){
                        if(column.scope.Round != null) {
                            cellValue = column.scope.Round.formatPercent(cellValue);
                        }
                        else{
                            cellValue = (cellValue * 100).toString() + "%";
                        }
                    }
                    else if(column.scope.ControlType == PublicEnum.ControlType.CheckBox){
                        if(cellValue){
                            cellValue = '<div class="Hook"/>'; //'&radic;';
                        }
                        else{
                            cellValue = '&nbsp;';
                        }
                    }
                    else if(column.scope.ControlType == PublicEnum.ControlType.Calendar){
                        if(cellValue == undefined || cellValue.trim() == "" || cellValue.constructor == undefined){
                            cellValue = '&nbsp;';
                        }
                        else if(cellValue.constructor == String){
                            cellValue = (PublicFunction.dateTimeToString(new Date(cellValue), column.scope.Type));
                        }
                        else if(cellValue.constructor == Date){
                            cellValue = (PublicFunction.dateTimeToString(new Date(cellValue), column.scope.Type));
                        }
                    }
                    else if(column.scope.ControlType == PublicEnum.ControlType.Refer){
                        var cellText;
                        if(column.scope.TextField.indexOf(".") > -1){
                            var fields = column.scope.TextField.split(".");
                            var strEvalField = "record";
                            for(var j=0; j<fields.length; j++){
                                strEvalField += "." + fields[j];
                                cellText = eval(strEvalField);
                                if(j < fields.length - 1){
                                    if(cellText == undefined || cellText == null || cellText.constructor != Object){
                                        eval(strEvalField + " = {}");
                                    }
                                }
                            }
                        }
                        else{
                            cellText = record[column.scope.TextField];
                        }

                        if(cellText != undefined){
                            cellValue = cellText.trim();
                        }
                        else{
                            cellValue = '&nbsp;';
                        }
                    }
                    else if(column.scope.ControlType == PublicEnum.ControlType.DropDownList) {
                        if(cellValue != undefined && cellValue !== "" && cellValue > -1) {
                            var isFind = false;
                            for(var option in column.scope.enum){
                                if(column.scope.enum[option].Value == cellValue){
                                    isFind = true;
                                    cellValue = column.scope.enum[option].Text;
                                    break;
                                }                                
                            }
                            if(!isFind){
                                cellValue = '&nbsp;';
                            }
                        }
                        else{
                            cellValue = '&nbsp;';
                        }
                    }

                    if(cellValue != "&nbsp;" && column.scope.ControlType != PublicEnum.ControlType.CheckBox){
                        newBodyRowCell.innerHTML += '<div title="' + cellValue + '">' + cellValue + '</div>';
                    }
                    else{
                        newBodyRowCell.innerHTML += '<div>' + cellValue + '</div>';
                    }
                    newBodyRowCell.children[0].setAttribute('class', column.scope.TextAlignClass);
                    newBodyRowCell.children[0].style.width = (Number(column.scope.Width.replace('px', '')) - 4).toString() + 'px';

                    newBodyRowCell.children[0].addEventListener('click', function () {
                        $scope.cellClick();
                    }, false);
                }

                //创建操作栏区域
                if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)){
                    var newBodyRightRow;
                    if(rowIndex != undefined && rowIndex >=0){
                        newBodyRightRow = $scope.Dom._BodyRightElement.insertRow(rowIndex);
                    }
                    else{
                        newBodyRightRow = $scope.Dom._BodyRightElement.insertRow();
                    }

                    if(this.FocusedRecord != null && record._id == this.FocusedRecord._id){
                        newBodyRightRow.style.backgroundColor = '#FAEBB2';
                    }
                    newBodyRightRow.setAttribute('key', record._id);
                    newBodyRightRow.addEventListener('click', function(){ $scope.rowClick(); }, true);
                    newBodyRightRow.addEventListener('dblclick', function(){ $scope.rowdblclick(); }, false);
                    var newBodyRightRowCell = newBodyRightRow.insertCell();

                    if($scope.Edit.IsAdd){
                        newBodyRightRowCell.innerHTML += '<img src="modules/Base/client/Images/addRow.png"/>';
                    }

                    if($scope.Edit.IsDelete){
                        if($scope.Edit.IsAdd){
                            newBodyRightRowCell.innerHTML += '<i>&nbsp;</i>';
                        }
                        newBodyRightRowCell.innerHTML += '<img src="modules/Base/client/Images/deleteRow.png"/>';
                    }

                    if($scope.Edit.IsAdd) {
                        newBodyRightRowCell.children[0].addEventListener('click', function () {
                            $scope.addRow();
                        }, false);

                        if($scope.Edit.IsDelete){
                            newBodyRightRowCell.children[2].addEventListener('click', function () {
                                $scope.deleteRow();
                            }, false);
                        }
                    }
                    else if($scope.Edit.IsDelete){
                        newBodyRightRowCell.children[0].addEventListener('click', function () {
                            $scope.deleteRow();
                        }, false);
                    }
                }
            };
            $scope.addRowsHtml = function(records){
                if(records != undefined && records.constructor == Array){
                    for(var i=0; i<records.length; i++){
                        $scope.addRowHtml(records[i]);
                    }
                }
            };
            $scope.deleteRowHtml = function(rowIndex){
                if(rowIndex == undefined || rowIndex >= $scope.Dom._BodyElement.rows.length){
                    rowIndex = $scope.Dom._BodyElement.rows.length - 1;
                }

                if($scope.IsSelect) {
                    $scope.Dom._BodyLeftElement.deleteRow(rowIndex);
                }
                $scope.Dom._BodyElement.deleteRow(rowIndex);
                if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)) {
                    $scope.Dom._BodyRightElement.deleteRow(rowIndex);
                }
            };
            $scope.deleteAllRowHtml = function(){
                while ($scope.Dom._BodyElement.rows.length > 0) {
                    $scope.deleteRowHtml();
                }
            };
            $scope.refresh = function(records){
                $scope.deleteAllRowHtml();                

                $scope.addRowsHtml(records);
                if ($scope.module.FocusedRecord != null) {
                    var focusedRow = getRowIndexById($scope.module.FocusedRecord._id);
                    if (focusedRow >= 0) {
                        if($scope.IsSelect) {
                            $scope.Dom._BodyLeftElement.rows[focusedRow].style.backgroundColor = '#FAEBB2';
                        }
                        $scope.Dom._BodyElement.rows[focusedRow].style.backgroundColor = '#FAEBB2';
                        if($scope.Edit.IsEdit && ($scope.Edit.IsAdd || $scope.Edit.IsDelete)) {
                            $scope.Dom._BodyRightElement.rows[focusedRow].style.backgroundColor = '#FAEBB2';
                        }
                        $scope.rowchange();
                    }
                }
            };
            $scope.refreshRows = function(records){
                for(var j=0; j<records.length; j++){
                    var record = records[j];
                    var rowIndex = getRowIndexById(record._id);
                    if(rowIndex != null){
                        for (var i = 0; i < $scope.Columns.length; i++){
                            var column = $scope.Columns[i];
                            var cellValue;
                            if(column.scope.ValueField.indexOf(".") > -1){
                                var fields = column.scope.ValueField.split(".");
                                var strEvalField = "record";
                                for(var n=0; n<fields.length; n++){
                                    strEvalField += "." + fields[n];
                                    cellValue = eval(strEvalField);
                                    if(n < fields.length - 1){
                                        if(cellValue == undefined || cellValue == null || cellValue.constructor != Object){
                                            cellValue = undefined;
                                            break;
                                        }
                                    }
                                }
                            }
                            else{
                                cellValue = record[column.scope.ValueField];
                            }

                            if(column.scope.ControlType == PublicEnum.ControlType.TextBox){
                                if(cellValue == undefined || cellValue == null || cellValue == ''){
                                    cellValue = '&nbsp;';
                                }
                            }
                            else if(column.scope.ControlType == PublicEnum.ControlType.NumberBox){
                                if(column.scope.Round != null) {
                                    cellValue = column.scope.Round.formatNumber(cellValue);
                                }
                            }
                            else if(column.scope.ControlType == PublicEnum.ControlType.PercentBox){
                                if(column.scope.Round != null) {
                                    cellValue = column.scope.Round.formatPercent(cellValue);
                                }
                                else{
                                    cellValue = (cellValue * 100).toString() + "%";
                                }
                            }
                            else if(column.scope.ControlType == PublicEnum.ControlType.CheckBox){
                                if(cellValue){
                                    cellValue = '<div class="Hook"/>'; //'&radic;';
                                }
                                else{
                                    cellValue = '&nbsp;';
                                }
                            }
                            else if(column.scope.ControlType == PublicEnum.ControlType.Calendar){
                                if(cellValue == undefined || cellValue.constructor == undefined){
                                    cellValue = '&nbsp;';
                                }
                                else if(cellValue.constructor == String){
                                    cellValue = (PublicFunction.dateTimeToString(new Date(cellValue), column.scope.Type));
                                }
                                else if(cellValue.constructor == Date){
                                    cellValue = (PublicFunction.dateTimeToString(new Date(cellValue), column.scope.Type));
                                }
                            }
                            else if(column.scope.ControlType == PublicEnum.ControlType.Refer){
                                var cellText;
                                if(column.scope.TextField.indexOf(".") > -1){
                                    var fields = column.scope.TextField.split(".");
                                    var strEvalField = "record";
                                    for(var j=0; j<fields.length; j++){
                                        strEvalField += "." + fields[j];
                                        cellText = eval(strEvalField);
                                        if(j < fields.length - 1){
                                            if(cellText == undefined || cellText == null || cellText.constructor != Object){
                                                eval(strEvalField + " = {}");
                                            }
                                        }
                                    }
                                }
                                else{
                                    cellText = record[column.scope.TextField];
                                }

                                if(cellText != undefined){
                                    cellValue = cellText.trim();
                                }
                                else{
                                    cellValue = '&nbsp;';
                                }
                            }
                            else if(column.scope.ControlType == PublicEnum.ControlType.DropDownList) {
                                if(cellValue != undefined && cellValue != "" && cellValue > -1) {
                                    var isFind = false;
                                    for(var option in column.scope.enum){
                                        if(column.scope.enum[option].Value == cellValue){
                                            isFind = true;
                                            cellValue = column.scope.enum[option].Text;
                                            break;
                                        }                                
                                    }
                                    if(!isFind){
                                        cellValue = '&nbsp;';
                                    }
                                }
                                else{
                                    cellValue = '&nbsp;';
                                }
                            }

                            $scope.Dom._BodyElement.rows[rowIndex].cells[i].children[0].innerHTML = cellValue;
                            if(cellValue != '&nbsp;' && column.scope.ControlType != PublicEnum.ControlType.CheckBox){
                                $scope.Dom._BodyElement.rows[rowIndex].cells[i].children[0].setAttribute("title", cellValue);
                            }
                        }
                    }
                }
            };
            $scope.refreshDeleteRows = function(records){
                for(var j=0; j<records.length; j++){
                    var rowIndex = getRowIndexById(records[j]._id);
                    if(rowIndex != null){
                        $scope.deleteRowHtml(rowIndex);
                    }
                }
            };
            $scope.loadByOrder = function(columnScope, spanElement){
                if($scope.module.QueryParameter.OrderBy == null || $scope.module.QueryParameter.OrderBy == undefined){
                    $scope.module.QueryParameter.OrderBy = {};
                }

                var orderName = columnScope.ValueField;
                if(orderName.indexOf(".") > -1){
                    orderName = orderName.split(".")[0];
                }

                if($scope.module.QueryParameter.OrderBy[orderName] == undefined){
                    $scope.module.QueryParameter.OrderBy[orderName] = 1;
                    spanElement.setAttribute("class", "glyphicon glyphicon-arrow-up DT_Order");
                }
                else if($scope.module.QueryParameter.OrderBy[orderName] == 1){
                    $scope.module.QueryParameter.OrderBy[orderName] = -1;
                    spanElement.setAttribute("class", "glyphicon glyphicon-arrow-down DT_Order");
                }
                else if($scope.module.QueryParameter.OrderBy[orderName] == -1){
                    delete $scope.module.QueryParameter.OrderBy[orderName];
                    spanElement.setAttribute("class", "");
                }

                if($scope.module.IsEntityModule){
                    $scope.module.load(null, null, $scope.order);
                }
                else{
                    $scope.module.sort(null, $scope.order);
                }
            };
            $scope.DataGrid_filterID = "";
            $scope.filterClick = function(){
                if($scope.DataGrid_filterID == ""){
                    $scope.DataGrid_filterID = (new Date()).getTime().toString();
                    var filterContentElement = $scope.Dom._tableDiv.parentElement.children[1].children[0].children[1].children[0].children[0].children[1];
                    $scope.filterCollection = []; 
                    var filterContentHtml = '<div style="width:100%;min-height:200px;max-height:450px;overflow:auto;">';
                    for(var i=0; i<$scope.Columns.length; i++){
                        if($scope.Columns[i].scope.IsFilter){
                            filterContentHtml += '<div class="row RowSpace">' + 
                                '<div class="LableDiv" style="width:120px;"><Label>' + $scope.Columns[i].scope.DisplayName + '</Label></div>' + 
                                '<div class="InputDiv" style="width:102px;">' + 
                                    '<DropDownList IsEmpty="false" change="filterCollection[' + i.toString() + '].ChangeEvent()" value="filterCollection[' + i.toString() + '].CompareRelationValue" Enum="filterCollection[' + i.toString() + '].CompareRelationEnum"></DropDownList>' + 
                                '</div>' + 
                                '<div class="InputDiv" style="width:280px;">';

                            var filterOption = {
                                Field: $scope.Columns[i].scope.ValueField,
                                DisplayName: $scope.Columns[i].scope.DisplayName,
                                ControlType: $scope.Columns[i].scope.ControlType,
                                CompareRelationEnum: null,
                                CompareRelationValue: PublicEnum.CompareRelation.No.Value,
                                Value: null,
                                Value2: null,
                                Enabled: false,
                                IsDisplayController2: false,
                                ChangeEvent: function(){
                                    if(this.CompareRelationValue == PublicEnum.CompareRelation.No.Value || 
                                        this.CompareRelationValue == PublicEnum.CompareRelation.Empty.Value || 
                                        this.CompareRelationValue == PublicEnum.CompareRelation.NoEmpty.Value){
                                        this.Enabled = false;
                                        this.Value = null;
                                        this.Value2 = null;
                                    }
                                    else{
                                        this.Enabled = true;
                                        if(this.CompareRelationValue == PublicEnum.CompareRelation.Between.Value){
                                            this.IsDisplayController2 = true;
                                        }
                                        else{
                                            this.IsDisplayController2 = false;
                                        }
                                    }
                                    $scope.$digest();
                                }
                            };
                            if($scope.Columns[i].scope.ControlType == PublicEnum.ControlType.TextBox) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Like: {Value: 1, Text: '包含'},
                                    NotLike: {Value: 2, Text: '不包含'},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    Empty: {Value: 12, Text: '空'},
                                    NoEmpty: {Value: 13, Text: '非空'}
                                };

                                filterContentHtml += '<TextBox value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></TextBox>';
                            }
                            else if($scope.Columns[i].scope.ControlType == PublicEnum.ControlType.NumberBox) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    GreatThen: {Value: 5, Text: '大于'},
                                    LessThan: {Value: 6, Text: '小于'},
                                    GreatThenEqual: {Value: 7, Text: '大于等于'},
                                    LessThanEqual: {Value: 8, Text: '小于等于'},
                                    Between: {Value: 11, Text: '两者之间'}
                                };

                                filterContentHtml += '<NumberBox value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></NumberBox>';
                                filterContentHtml += '<NumberBox visible="{{filterCollection[' + i.toString() + '].IsDisplayController2}}" style="margin-top:5px;" value="filterCollection[' + i.toString() + '].Value2" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></NumberBox>';
                            }
                            else if($scope.Columns[i].scope.ControlType == PublicEnum.ControlType.PercentBox) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    GreatThen: {Value: 5, Text: '大于'},
                                    LessThan: {Value: 6, Text: '小于'},
                                    GreatThenEqual: {Value: 7, Text: '大于等于'},
                                    LessThanEqual: {Value: 8, Text: '小于等于'},
                                    Between: {Value: 11, Text: '两者之间'}
                                };

                                filterContentHtml += '<PercentBox value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></PercentBox>';
                                filterContentHtml += '<PercentBox style="margin-top:5px;" visible="{{filterCollection[' + i.toString() + '].IsDisplayController2}}" value="filterCollection[' + i.toString() + '].Value2" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></PercentBox>';
                            }
                            else if($scope.Columns[i].scope.ControlType == PublicEnum.ControlType.CheckBox) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'}
                                };
                                filterContentHtml += '<CheckBox value="filterCollection[' + i.toString() + '].Value"></CheckBox>';
                            }
                            else if($scope.Columns[i].scope.ControlType == PublicEnum.ControlType.DropDownList) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'}
                                };
                                filterContentHtml += '<DropDownList enum="Columns[' + i.toString() + '].scope.enum" value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></DropDownList>';
                            }
                            else if($scope.Columns[i].scope.ControlType == PublicEnum.ControlType.Refer) {
                                filterOption.Field = filterOption.Field.split(".")[0];
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    Empty: {Value: 12, Text: '空'},
                                    NoEmpty: {Value: 13, Text: '非空'}
                                };

                                filterContentHtml += '<Refer IsInclude="true" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}" Condition="' + $scope.Columns[i].scope.QueryParameter.Condition + '" ' + 
                                    'OrderBy="' + $scope.Columns[i].scope.QueryParameter.OrderBy + '" ' + 
                                    'Populate="' + $scope.Columns[i].scope.QueryParameter.Populate + '" ' +
                                    'key="filterCollection[' + i.toString() + '].Value.Key" value="filterCollection[' + i.toString() + '].Value.Value" text="filterCollection[' + i.toString() + '].Value.Text" ' + 
                                    'keyfield="' + $scope.Columns[i].scope.BindKeyField + '" valuefield="' + $scope.Columns[i].scope.BindValueField + '" textfield="' + $scope.Columns[i].scope.BindTextField + '" ' + 
                                    'EntityName="' + $scope.Columns[i].scope.EntityName + '" windowtitle="' + $scope.Columns[i].scope.WindowTitle + '">';

                                for(var j=0; j<$scope.Columns[i].scope.Columns.length; j++){
                                    var columnHtml = '<Column'
                                    if ($scope.Columns[i].scope.Columns[j].Type != undefined && $scope.Columns[i].scope.Columns[j].Type != "") {
                                        columnHtml += ' type="' + $scope.Columns[i].scope.Columns[j].Type + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].DisplayName != undefined && $scope.Columns[i].scope.Columns[j].DisplayName != "") {
                                        columnHtml += ' displayname="' + $scope.Columns[i].scope.Columns[j].DisplayName + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].Width != undefined && $scope.Columns[i].scope.Columns[j].Width != "") {
                                        columnHtml += ' width="' + $scope.Columns[i].scope.Columns[j].Width + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].ValueField != undefined && $scope.Columns[i].scope.Columns[j].ValueField != "") {
                                        columnHtml += ' valuefield="' + $scope.Columns[i].scope.Columns[j].ValueField + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].Enum != undefined && $scope.Columns[i].scope.Columns[j].Enum != "") {
                                        columnHtml += ' enum="' + $scope.Columns[i].scope.Columns[j].Enum + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].Round != undefined && $scope.Columns[i].scope.Columns[j].Round != "") {
                                        columnHtml += ' round="' + $scope.Columns[i].scope.Columns[j].Round + '"';
                                    }
                                    if ($scope.Columns[i].scope.Columns[j].CalendarType != undefined && $scope.Columns[i].scope.Columns[j].CalendarType != "") {
                                        columnHtml += ' calendartype="' + $scope.Columns[i].scope.Columns[j].CalendarType + '"';
                                    }
                                    columnHtml += '></Column>';
                                    filterContentHtml += columnHtml;
                                }
                                filterContentHtml += '</Refer>';
                            }
                            else if($scope.Columns[i].scope.ControlType == PublicEnum.ControlType.Calendar) {
                                filterOption.CompareRelationEnum = {
                                    No: {Value: 0, Text: ''},
                                    Equal: {Value: 3, Text: '等于'},
                                    NoEqual: {Value: 4, Text: '不等于'},
                                    GreatThen: {Value: 5, Text: '大于'},
                                    LessThan: {Value: 6, Text: '小于'},
                                    GreatThenEqual: {Value: 7, Text: '大于等于'},
                                    LessThanEqual: {Value: 8, Text: '小于等于'},
                                    Between: {Value: 11, Text: '两者之间'}
                                };
                                if($scope.Columns[i].scope.Type == PublicEnum.DateTimeFormat.Date){
                                    filterContentHtml += '<Calendar type="date" value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></Calendar>';
                                    filterContentHtml += '<Calendar style="margin-top:5px;" type="date" visible="{{filterCollection[' + i.toString() + '].IsDisplayController2}}" value="filterCollection[' + i.toString() + '].Value2" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></Calendar>';
                                }
                                else{
                                    filterContentHtml += '<Calendar type="datetime" value="filterCollection[' + i.toString() + '].Value" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></Calendar>';
                                    filterContentHtml += '<Calendar style="margin-top:5px;" visible="{{filterCollection[' + i.toString() + '].IsDisplayController2}}" type="datetime" value="filterCollection[' + i.toString() + '].Value2" Enabled="{{filterCollection[' + i.toString() + '].Enabled}}"></Calendar>';
                                }
                            }

                            $scope.filterCollection.push(filterOption);
                            filterContentHtml += '</div></div>';
                        }
                    }
                    filterContentHtml += '</div>';

                    $compile(filterContentHtml)($scope, function (clone, $scope) {
                        filterContentElement.appendChild(clone[0]);
                    });
                }
            };
            $scope.btnFilterOKClick = function(){
                $('#' + $scope.DataGrid_filterID).modal('hide');

                var objWhere = {};
                if($scope.module.QueryParameter.FixedCondition != undefined &&
                    $scope.module.QueryParameter.FixedCondition != null){
                    objWhere = $scope.module.QueryParameter.FixedCondition;
                }
                for(var i=0; i<$scope.filterCollection.length; i++){
                    if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.Like.Value){
                        objWhere[$scope.filterCollection[i].Field] = '/' + $scope.filterCollection[i].Value + '/';
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.NotLike.Value){
                        objWhere[$scope.filterCollection[i].Field] = {$not: '/' + $scope.filterCollection[i].Value + '/'};                        
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.Equal.Value){
                        if($scope.filterCollection[i].ControlType == PublicEnum.ControlType.Calendar){
                            var date = new Date($scope.filterCollection[i].Value);
                            var date1 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                            var date2 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                            date2.setSeconds(date2.getSeconds() + 1);
                            objWhere[$scope.filterCollection[i].Field] = {$gte: date1.toString(), $lt: date2.toString()};
                        }
                        else if($scope.filterCollection[i].ControlType == PublicEnum.ControlType.Refer){
                            objWhere[$scope.filterCollection[i].Field] = {$eq: $scope.filterCollection[i].Value.Key};
                        }
                        else{
                            objWhere[$scope.filterCollection[i].Field] = {$eq: $scope.filterCollection[i].Value};
                        }
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.NoEqual.Value){
                        if($scope.filterCollection[i].ControlType == PublicEnum.ControlType.Calendar){
                            var date = new Date($scope.filterCollection[i].Value);
                            var date1 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                            var date2 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                            date2.setSeconds(date2.getSeconds() + 1);
                            var condition1 = {};
                            condition1[$scope.filterCollection[i].Field] = {'$lt': date1.toString()};
                            var condition2 = {};
                            condition2[$scope.filterCollection[i].Field] = {'$gte': date2.toString()};
                            objWhere['$or'] = [condition1, condition2];
                        }
                        else{
                            objWhere[$scope.filterCollection[i].Field] = {$ne: $scope.filterCollection[i].Value};
                        }
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.GreatThen.Value){
                        if($scope.filterCollection[i].ControlType == PublicEnum.ControlType.Calendar){
                            var date = new Date($scope.filterCollection[i].Value);
                            var date1 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                            date1.setSeconds(date1.getSeconds() + 1);
                            objWhere[$scope.filterCollection[i].Field] = {$gte: date1.toString()};
                        }
                        else{
                            objWhere[$scope.filterCollection[i].Field] = {$gt: $scope.filterCollection[i].Value};
                        }
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.LessThan.Value){
                        if($scope.filterCollection[i].ControlType == PublicEnum.ControlType.Calendar){
                            var date = new Date($scope.filterCollection[i].Value);
                            var date1 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                            objWhere[$scope.filterCollection[i].Field] = {$lt: date1.toString()};
                        }
                        else{
                            objWhere[$scope.filterCollection[i].Field] = {$lt: $scope.filterCollection[i].Value};
                        }
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.GreatThenEqual.Value){
                        if($scope.filterCollection[i].ControlType == PublicEnum.ControlType.Calendar){
                            var date = new Date($scope.filterCollection[i].Value);
                            var date1 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                            objWhere[$scope.filterCollection[i].Field] = {$gte: date1.toString()};
                        }
                        else{
                            objWhere[$scope.filterCollection[i].Field] = {$gte: $scope.filterCollection[i].Value};
                        }
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.LessThanEqual.Value){
                        if($scope.filterCollection[i].ControlType == PublicEnum.ControlType.Calendar){
                            var date = new Date($scope.filterCollection[i].Value);
                            var date1 = new Date(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds());
                            date1.setSeconds(date1.getSeconds() + 1);
                            objWhere[$scope.filterCollection[i].Field] = {$lt: date1.toString()};
                        }
                        else{
                            objWhere[$scope.filterCollection[i].Field] = {$lte: $scope.filterCollection[i].Value};
                        }
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.Empty.Value){
                        objWhere[$scope.filterCollection[i].Field] = null;
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.NoEmpty.Value){
                        objWhere[$scope.filterCollection[i].Field] = {$ne: null};
                    }
                    else if($scope.filterCollection[i].CompareRelationValue == PublicEnum.CompareRelation.Between.Value){
                        if($scope.filterCollection[i].ControlType == PublicEnum.ControlType.Calendar){
                            var date1 = new Date($scope.filterCollection[i].Value);
                            date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate(), date1.getHours(), date1.getMinutes(), date1.getSeconds());
                            var date2 = new Date($scope.filterCollection[i].Value2);
                            date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate(), date2.getHours(), date2.getMinutes(), date2.getSeconds());
                            date2.setSeconds(date2.getSeconds() + 1);
                            objWhere[$scope.filterCollection[i].Field] = {
                                $gte: new Date(date1.toString()),
                                $lt: new Date(date2.toString())
                            };
                        }
                        else{
                            objWhere[$scope.filterCollection[i].Field] = {
                                $gte: $scope.filterCollection[i].Value,
                                $lte: $scope.filterCollection[i].Value2
                            };
                        }
                    }
                }

                $scope.module.QueryParameter.Condition = objWhere;
                $scope.module.load();
            };
            $scope.btnFilterCancelClick = function(){
                $('#' + $scope.DataGrid_filterID).modal('hide');
            };
        }],
        link: function (scope, element, attrs) {
            scope.ID = "";
            scope.Width = '100%';
            scope.Height = '100%';
            scope.IsSelect = false;    //是否支持选择
            scope.IsFilter = true;

            if (attrs["id"] != undefined && attrs["id"].trim() != "") {
                scope.ID = attrs["id"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
            }
            if (attrs["height"] != undefined && attrs["height"].trim() != "") {
                scope.Height = attrs["height"].trim();
            }
            if (attrs["isselect"] != undefined && attrs["isselect"].toLocaleLowerCase() == "true") {
                scope.IsSelect = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isedit"] != undefined && attrs["isedit"].toLocaleLowerCase() == "false") {
                scope.Edit.IsEdit = false;
            }
            if (attrs["isadd"] != undefined && attrs["isadd"].toLocaleLowerCase() == "false") {
                scope.Edit.IsAdd = false;
            }
            if (attrs["ismodify"] != undefined && attrs["ismodify"].toLocaleLowerCase() == "false") {
                scope.Edit.IsModify = false;
            }
            if (attrs["isdelete"] != undefined && attrs["isdelete"].toLocaleLowerCase() == "false") {
                scope.Edit.IsDelete = false;
            }
            
            //以下是表格的拖动处理代码
            var tableBody = element[0].children[0];
            var tableFooter = element[0].children[1];

            if(scope.IsFilter){
                tableFooter.children[1].style.paddingLeft = "33px";
            }

            scope.Dom = {
                _tableDiv: tableBody,
                _addRowDiv: tableBody.children[1],
                _HeadLeftElement: tableBody.children[0].rows[0].cells[0].children[0],
                _HeadElement: tableBody.children[0].rows[0].cells[1].children[0],
                _HeadRightElement: tableBody.children[0].rows[0].cells[2].children[0],
                _BodyLeftElement: tableBody.children[0].rows[1].cells[0].children[0],
                _BodyElement: tableBody.children[0].rows[1].cells[1].children[0],
                _BodyRightElement: tableBody.children[0].rows[1].cells[2].children[0],

                _IsHeadMouseDown: false,
                _HeadMouseDownTD: null,
                _HeadMouseDownX: 0,
                _MouseMoveLine: null,
                _HeadChangeWidthTD: null
            };

            scope._scroll = function () {
                scope.Dom._HeadLeftElement.style.top = event.srcElement.scrollTop + 'px';
                scope.Dom._HeadLeftElement.style.left = event.srcElement.scrollLeft + 'px';
                scope.Dom._HeadElement.style.top = event.srcElement.scrollTop + 'px';
                scope.Dom._BodyLeftElement.style.left = event.srcElement.scrollLeft + 'px';

                if (scope.Edit.IsEdit) {
                    scope.Dom._HeadRightElement.style.top = event.srcElement.scrollTop + 'px';
                }
            };
            scope._mouseDown = function () {
                if (event.srcElement.tagName != "TD") {
                    return;
                }

                scope.Dom._HeadMouseDownX = event.clientX;
                scope.Dom._HeadMouseDownTD = event.srcElement;
                scope.Dom._HeadChangeWidthTD = event.srcElement;

                if (scope.Dom._HeadMouseDownX < scope.Dom._HeadChangeWidthTD.getBoundingClientRect().right - 5) {
                    if (scope.Dom._HeadChangeWidthTD.cellIndex == 0) {
                        scope.Dom._HeadChangeWidthTD = scope.Dom._HeadLeftElement.rows[0].cells[0];
                        if(!scope.IsSelect){
                            return;
                        }
                    }
                    else {
                        scope.Dom._HeadChangeWidthTD = scope.Dom._HeadElement.rows[0].cells[scope.Dom._HeadChangeWidthTD.cellIndex - 1];
                    }
                }

                scope.Dom._IsHeadMouseDown = true;
                scope.Dom._HeadMouseDownTD.style.cursor = "col-resize";
                scope.Dom._MouseMoveLine = document.createElement("div");
                scope.Dom._MouseMoveLine.className = "DivLine";
                scope.Dom._MouseMoveLine.style.height = scope.Dom._tableDiv.clientHeight.toString() + 'px';
                scope.Dom._MouseMoveLine.style.left = event.clientX.toString() + 'px';
                scope.Dom._MouseMoveLine.style.top = (scope.Dom._tableDiv.getBoundingClientRect().top + document.body.scrollTop).toString() + 'px';
                document.body.appendChild(scope.Dom._MouseMoveLine);

                window.addEventListener('mousemove', scope._mouseMove, false);
                window.addEventListener('mouseup', scope._mouseUp, false);
            };
            scope._mouseUp = function () {
                if (scope.Dom._IsHeadMouseDown) {
                    scope.Dom._IsHeadMouseDown = false;

                    if (scope.Dom._HeadMouseDownTD != null) {
                        window.removeEventListener('mousemove', scope._mouseMove, false);
                        window.removeEventListener('mouseup', scope._mouseUp, false);
                        //_HeadMouseDownTD.releaseCapture();
                        //window.releaseEvents(Event.MOUSEMOVE|Event.MOUSEUP);
                    }

                    scope.Dom._HeadMouseDownTD.style.cursor = "e-resize";
                    scope.Dom._HeadMouseDownTD = null;

                    if (scope.Dom._HeadChangeWidthTD.offsetWidth + event.clientX - scope.Dom._HeadMouseDownX <= 10) {
                        if (scope.Dom._HeadChangeWidthTD == scope.Dom._HeadLeftElement.rows[0].cells[0]) {
                            scope.CheckColumn.Width = '10px';
                        }
                        else {
                            scope.Columns[scope.Dom._HeadChangeWidthTD.cellIndex].scope.Width = '10px';
                        }
                    }
                    else {
                        var widh = scope.Dom._HeadChangeWidthTD.offsetWidth + event.clientX - scope.Dom._HeadMouseDownX;
                        if (scope.Dom._HeadChangeWidthTD == scope.Dom._HeadLeftElement.rows[0].cells[0]) {
                            scope.CheckColumn.Width = (widh - 4).toString() + "px";
                        }
                        else {
                            scope.Columns[scope.Dom._HeadChangeWidthTD.cellIndex].scope.Width = widh.toString() + "px";
                        }
                    }

                    var rowCount = scope.Dom._BodyElement.rows.length;
                    var cellWidth;
                    if(scope.Dom._HeadChangeWidthTD == scope.Dom._HeadLeftElement.rows[0].cells[0]){
                        cellWidth = scope.CheckColumn.Width;
                        for(var i=0; i<rowCount; i++) {
                            scope.Dom._BodyLeftElement.rows[i].cells[0].children[0].style.width = cellWidth;
                        }
                    }
                    else{
                        var cellIndex = scope.Dom._HeadChangeWidthTD.cellIndex;
                        scope.Columns[cellIndex].scope.$digest();
                        cellWidth = (Number(scope.Columns[cellIndex].scope.Width.replace('px', '')) - 4).toString() + 'px';
                        scope.Dom._BodyElement.children[0].children[cellIndex].setAttribute('width', scope.Columns[cellIndex].scope.Width);
                        for(var i=0; i<rowCount; i++){
                            scope.Dom._BodyElement.rows[i].cells[cellIndex].children[0].style.width = cellWidth;
                        }
                    }

                    scope.$digest();

                    scope.Dom._HeadChangeWidthTD = null;
                    scope.Dom._HeadMouseDownX = null;
                    document.body.removeChild(scope.Dom._MouseMoveLine);
                }
            };
            scope._mouseMove = function () {
                if (scope.Dom._IsHeadMouseDown) {
                    scope.Dom._MouseMoveLine.style.left = event.clientX + 'px';
                }
            };

            scope.Dom._addRowDiv.children[0].addEventListener('click', function () {
                            scope.btnAdd();
            }, false);
            scope.Dom._tableDiv.addEventListener('scroll', scope._scroll, false);
            //对头部TD赋mousedown事件
            scope.Dom._HeadLeftElement.rows[0].cells[0].addEventListener('mousedown', scope._mouseDown, false);
            for (var i = 0; i < scope.Columns.length; i++) {
                var column = scope.Columns[i];
                scope.Dom._BodyElement.children[0].innerHTML += '<col width="' + column.scope.Width + '"/>';
                scope.Dom._HeadElement.rows[0].cells[i].addEventListener('mousedown', scope._mouseDown, false);

                if (!column.scope.IsDisplay) {
                    scope.Dom._BodyElement.children[0].children[i].style.display = 'none';
                }
            }

            if(scope.module != undefined && scope.module != null){
                scope.$on(scope.module._ID, function(event, records){
                    scope.refresh(records);
                });
                scope.$on("RefreshRows" + scope.module._ID, function(event, records){
                    if(records == undefined)
                    {
                        records = [scope.module.FocusedRecord];
                    }
                    scope.refreshRows(records);
                });
                scope.$on("RefreshDeleteRows" + scope.module._ID, function(event, records){
                    if(records == undefined)
                    {
                        records = [scope.module.FocusedRecord];
                    }
                    scope.refreshDeleteRows(records);
                });
            }
        }
    }
}]);

app.directive("textboxcolumn", ['PublicEnum', function(PublicEnum) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
            '<td ng-show="IsDisplay">' +
                '<div style="display: none">' +
                    '<TextBox class="GridBaseControl" change="change()" blur="blur()" value="value" isempty="{{scope.IsEmpty.toString()}}"></TextBox>' +
                '</div>' +
                '<!--支持列头点击事件-->' +
                '<div style="width: {{DivWidth}}" ng-if="IsTitleClick" ng-click="order()">' +
                    '<u style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                    '<i ng-if="IsOrder">&nbsp;</i>' +
                    '<span ng-if="IsOrder" class="glyphicon glyphicon-menu-down"/>' +
                '</div>' +
                '<!--不支持列头点击事件-->' +
                '<div style="width: {{DivWidth}}" ng-if="!IsTitleClick" ng-click="order()">' +
                    '<span>{{DisplayName}}</span>' +
                    '<i ng-if="IsOrder">&nbsp;</i>' +
                    '<span ng-if="IsOrder" class=""/>' +
                '</div>' +
            '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControlType = PublicEnum.ControlType.TextBox;
            scope.TextAlignClass = 'TextLeftAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function(){
                scope.titleclick();
            };
            scope.filterClick = function(){
                alert('filterClick');
            };
            scope.order = function(){
                dataGridCtrl.scope.loadByOrder(scope, element[0].children[1].children[2]);
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                scope.value = scope.value.trim();
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") > -1){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = eval("record." + scope.ValueField);
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = '" + scope.value + "'");
                    dataGridCtrl.scope.cellvaluechange(
                        {
                            columnName: scope.ValueField,
                            newValue: scope.value,
                            oldValue: oldValue
                        }
                    );
                    dataGridCtrl.scope.$digest();
                }
            };
            scope.blur = function(){
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(scope.value != undefined && scope.value != null && scope.value !== '') {
                    td.children[0].innerText = scope.value;
                    td.children[0].setAttribute("title", scope.value);
                }
                else{
                    td.children[0].removeAttribute("title");
                    td.children[0].innerHTML = '&nbsp;';
                }
                td.children[0].style.display = '';
            };

            element[0].children[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}]);

app.directive("numberboxcolumn", ['PublicEnum', 'PublicClass', function(PublicEnum, PublicClass) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
            '<td>' +
                '<div style="display: none">' +
                    '<NumberBox class="GridBaseControl" change="change()" blur="blur()" value="value" isempty="{{scope.IsEmpty.toString()}}"></NumberBox>' +
                '</div>' +
                '<!--支持列头点击事件-->' +
                '<div style="width: {{DivWidth}}" ng-if="IsTitleClick" ng-click="order()">' +
                    '<u style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                    '<i ng-if="IsOrder">&nbsp;</i>' +
                    '<span ng-if="IsOrder" class="glyphicon glyphicon-menu-down"/>' +
                '</div>' +
                '<!--不支持列头点击事件-->' +
                '<div style="width: {{DivWidth}}" ng-if="!IsTitleClick" ng-click="order()">' +
                    '<span>{{DisplayName}}</span>' +
                    '<i ng-if="IsOrder">&nbsp;</i>' +
                    '<span ng-if="IsOrder" class=""/>' +
                '</div>' +
            '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControlType = PublicEnum.ControlType.NumberBox;
            scope.TextAlignClass = 'TextRightAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.Round = null;
            scope.MinValue = null;
            scope.MaxValue = null;

            if (attrs["round"] != undefined && attrs["round"].trim() != "") {
                scope.Round = eval("(" + attrs["round"].trim() + ")");

                var precision = scope.Round.Precision;
                var roundType = PublicEnum.RoundType.AccondValueRound;
                var roundValue = 5;
                
                if(scope.Round.Precision != undefined){
                    precision = scope.Round.Precision;
                }
                if(scope.Round.RoundType != undefined){
                    roundType = scope.Round.RoundType;
                }
                if(scope.Round.RoundValue != undefined){
                    roundValue = scope.Round.RoundValue;
                }

                scope.Round = new PublicClass.Round(precision, roundType, roundValue);
            }
            if (attrs["minvalue"] != undefined && attrs["minvalue"].trim() != "") {
                scope.MinValue = parseFloat(attrs["minvalue"].trim());
            }
            if (attrs["maxvalue"] != undefined && attrs["maxvalue"].trim() != "") {
                scope.MaxValue = parseFloat(attrs["maxvalue"].trim());
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }

            scope.$$childHead.Round = scope.Round;
            scope.$$childHead.MinValue = scope.MinValue;
            scope.$$childHead.MaxValue = scope.MaxValue;
            scope.$$childHead.IsEmpty = scope.IsEmpty;

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function () {
                scope.titleclick();
            };
            scope.filterClick = function () {
                alert('filterClick');
            };
            scope.order = function(){
                dataGridCtrl.scope.loadByOrder(scope, element[0].children[1].children[2]);
            };

            scope.keyDown = function () {
                dataGridCtrl.scope.keyDown();
                if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") > -1){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = eval("record." + scope.ValueField);
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = " + scope.value.toString());
                    dataGridCtrl.scope.cellvaluechange(
                        {
                            columnName: scope.ValueField,
                            newValue: scope.value,
                            oldValue: oldValue
                        }
                    );
                    dataGridCtrl.scope.$digest();
                }
            };
            scope.blur = function () {
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(event.srcElement.value != '') {
                    if(scope.Round != null){
                        td.children[0].innerText = scope.Round.formatNumber(scope.value);
                    }
                    else{
                        td.children[0].innerText = $scope.value;
                    }
                    td.children[0].setAttribute("title", td.children[0].innerText);
                }
                else{
                    td.children[0].innerHTML = '&nbsp;';
                    td.children[0].removeAttribute("title");
                }
                
                td.children[0].style.display = '';
            };

            element[0].children[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function () {
                    return attrs["isedit"];
                },
                function () {
                    if (attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false') {
                        scope.IsEdit = false;
                    }
                    else {
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function () {
                    return attrs["isdisplay"];
                },
                function () {
                    if (attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false') {
                        scope.IsDisplay = false;
                    }
                    else {
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}]);

app.directive("percentboxcolumn", ['PublicEnum', 'PublicClass', function(PublicEnum, PublicClass) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
        '<td ng-show="IsDisplay">' +
            '<div style="display: none">' +
                '<PercentBox class="GridBaseControl" change="change()" blur="blur()" value="value" isempty="{{scope.IsEmpty.toString()}}"></PercentBox>' +
            '</div>' +
            '<!--支持列头点击事件-->' +
            '<div style="width: {{DivWidth}}" ng-if="IsTitleClick" ng-click="order()">' +
                '<u style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" class="glyphicon glyphicon-menu-down"/>' +
            '</div>' +
            '<!--不支持列头点击事件-->' +
            '<div style="width: {{DivWidth}}" ng-if="!IsTitleClick" ng-click="order()">' +
                '<span>{{DisplayName}}</span>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" class=""/>' +
            '</div>' +
        '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControlType = PublicEnum.ControlType.PercentBox;
            scope.TextAlignClass = 'TextRightAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.Round = null;
            scope.MinValue = null;
            scope.MaxValue = null;

            if (attrs["round"] != undefined && attrs["round"].trim() != "") {
                scope.Round = eval("(" + attrs["round"].trim() + ")");

                var precision = scope.Round.Precision;
                var roundType = PublicEnum.RoundType.AccondValueRound;
                var roundValue = 5;

                if(scope.Round.RoundType != undefined){
                    roundType = scope.Round.RoundType;
                }
                if(scope.Round.RoundValue != undefined){
                    roundValue = scope.Round.RoundValue;
                }

                scope.Round = new PublicClass.Round(precision, roundType, roundValue);
            }
            if (attrs["minvalue"] != undefined && attrs["minvalue"].trim() != "") {
                scope.MinValue = parseFloat(attrs["minvalue"].trim());
            }
            if (attrs["maxvalue"] != undefined && attrs["maxvalue"].trim() != "") {
                scope.MaxValue = parseFloat(attrs["maxvalue"].trim());
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }

            scope.$$childHead.Round = scope.Round;
            scope.$$childHead.MinValue = scope.MinValue;
            scope.$$childHead.MaxValue = scope.MaxValue;
            scope.$$childHead.IsEmpty = scope.IsEmpty;

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function () {
                scope.titleclick();
            };
            scope.filterClick = function () {
                alert('filterClick');
            };
            scope.order = function(){
                dataGridCtrl.scope.loadByOrder(scope, element[0].children[1].children[2]);
            };

            scope.keyDown = function () {
                dataGridCtrl.scope.keyDown();
                if (event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") > -1){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = eval("record." + scope.ValueField);
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = " + scope.value.toString());
                    dataGridCtrl.scope.cellvaluechange(
                        {
                            columnName: scope.ValueField,
                            newValue: scope.value,
                            oldValue: oldValue
                        }
                    );
                    dataGridCtrl.scope.$digest();
                }
            };
            scope.blur = function () {
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(event.srcElement.value != '') {
                    if(scope.Round != null){
                        td.children[0].innerText = scope.Round.formatPercent(scope.value);
                    }
                    else{
                        td.children[0].innerText = $scope.value;
                    }
                    td.children[0].setAttribute("title", td.children[0].innerText);
                }
                else{
                    td.children[0].innerHTML = '&nbsp;';
                    td.children[0].removeAttribute("title");
                }
                td.children[0].style.display = '';
            };

            element[0].children[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function () {
                    return attrs["isedit"];
                },
                function () {
                    if (attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false') {
                        scope.IsEdit = false;
                    }
                    else {
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function () {
                    return attrs["isdisplay"];
                },
                function () {
                    if (attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false') {
                        scope.IsDisplay = false;
                    }
                    else {
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}]);

app.directive("checkboxcolumn", ['PublicEnum', function(PublicEnum) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
        '<td ng-show="IsDisplay">' +
            '<div style="display: none">' +
                '<CheckBox blur="blur()" change="change()" style="outline:none;" value="value"></CheckBox>' +
            '</div>' +
            '<!--支持列头点击事件-->' +
            '<div style="width: {{DivWidth}}" ng-if="IsTitleClick" ng-click="order()">' +
                '<u style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" class="glyphicon glyphicon-menu-down"/>' +
            '</div>' +
            '<!--不支持列头点击事件-->' +
            '<div style="width: {{DivWidth}}" ng-if="!IsTitleClick" ng-click="order()">' +
                '<span>{{DisplayName}}</span>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" class=""/>' +
            '</div>' +
        '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.Data = {value: false};
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControlType = PublicEnum.ControlType.CheckBox;
            scope.TextAlignClass = 'TextCenterAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function(){
                scope.titleclick();
            };
            scope.filterClick = function(){
                alert('filterClick');
            };
            scope.order = function(){
                dataGridCtrl.scope.loadByOrder(scope, element[0].children[1].children[2]);
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 32 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") > -1){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = eval("record." + scope.ValueField);
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = " + scope.value.toString());
                    dataGridCtrl.scope.cellvaluechange(
                        {
                            columnName: scope.ValueField,
                            newValue: scope.value,
                            oldValue: oldValue
                        }
                    );
                    dataGridCtrl.scope.$digest();
                }
            };
            scope.blur = function(){
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(scope.value) {
                    td.children[0].innerHTML = '<div class="Hook"/>'; //'&radic;';
                }
                else{
                    td.children[0].innerHTML = '&nbsp;';
                }
                td.children[0].style.display = '';
            };

            element[0].children[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );

            scope.$watch(
                function(){
                    return scope.value;
                },
                function(){
                    scope.Data.value = scope.value;
                }
            );
            scope.$watch(
                function(){
                    return scope.Data.value;
                },
                function(){
                    scope.value = scope.Data.value;
                }
            );
            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}]);

app.directive("calendarcolumn", ['PublicEnum', 'PublicFunction', function(PublicEnum, PublicFunction) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&'
        },
        template:
        '<td ng-show="IsDisplay">' +
            '<div style="display: none">' +
                '<Calendar class="GridBaseControl" change="change()" blur="blur()" style="overflow: visible;" type="Type" value="value" isempty="{{scope.IsEmpty.toString()}}" isgrid="true"></Calendar>' +
            '</div>' +
            '<!--支持列头点击事件-->' +
            '<div style="width: {{DivWidth}}" ng-if="IsTitleClick" ng-click="order()">' +
                '<u style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" class="glyphicon glyphicon-menu-down"/>' +
            '</div>' +
            '<!--不支持列头点击事件-->' +
            '<div style="width: {{DivWidth}}" ng-if="!IsTitleClick" ng-click="order()">' +
                '<span>{{DisplayName}}</span>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" class=""/>' +
            '</div>' +
        '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControlType = PublicEnum.ControlType.Calendar;
            scope.TextAlignClass = 'TextLeftAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.Type = PublicEnum.DateTimeFormat.DateTime;
            scope.IsControlDisplay = false;

            if (attrs["type"] != undefined && attrs["type"].trim() == "date") {
                scope.Type = PublicEnum.DateTimeFormat.Date;
            }
            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function(){
                scope.titleclick();
            };
            scope.filterClick = function(){
                alert('filterClick');
            };
            scope.order = function(){
                dataGridCtrl.scope.loadByOrder(scope, element[0].children[1].children[2]);
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") > -1){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = eval("record." + scope.ValueField);
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = '" + scope.value + "'");
                    dataGridCtrl.scope.cellvaluechange(
                        {
                            columnName: scope.ValueField,
                            newValue: scope.value,
                            oldValue: oldValue
                        }
                    );
                    dataGridCtrl.scope.$digest();
                }
            };
            scope.blur = function(){
                var tdElement = calendarElement.parentNode;

                element[0].children[0].appendChild(calendarElement);
                if(scope.value != '') {
                    tdElement.children[0].innerText = PublicFunction.dateTimeToString(new Date(scope.value));
                    tdElement.children[0].setAttribute("title", td.children[0].innerText);
                }
                else{
                    tdElement.children[0].innerHTML = '&nbsp;';
                    tdElement.children[0].removeAttribute("title");
                }
                tdElement.children[0].style.display = '';
            };

            var calendarElement = element[0].children[0].children[0];
            var inputElement = calendarElement.children[0];
            inputElement.addEventListener('keydown', scope.keyDown, false);

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}]);

app.directive("refercolumn", ['$compile','PublicEnum', 'PublicFunction', function($compile, PublicEnum, PublicFunction) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            titleclick: '&',
            change: '&',
            beforeshow: '&'
        },
        template:
        '<td ng-show="IsDisplay">' +
            '<div style="display: none" ng-transclude>' +
            '</div>' +
            '<!--支持列头点击事件-->' +
            '<div style="width: {{DivWidth}}" ng-if="IsTitleClick" ng-click="order()">' +
                '<u style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" class="glyphicon glyphicon-menu-down"/>' +
            '</div>' +
            '<!--不支持列头点击事件-->' +
            '<div style="width: {{DivWidth}}" ng-if="!IsTitleClick" ng-click="order()">' +
                '<span>{{DisplayName}}</span>' +
                '<i ng-if="IsOrder">&nbsp;</i>' +
                '<span ng-if="IsOrder" class=""/>' +
            '</div>' +
        '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.key;
            scope.value;
            scope.text;
            scope.KeyField = '_id';
            scope.ValueField = 'code';
            scope.TextField = 'name';
            scope.EntityName;
            scope.WindowTitle;
            scope.IsSelect = false;
            scope.QueryParameter = {};

            scope.ControlType = PublicEnum.ControlType.Refer;
            scope.TextAlignClass = 'TextLeftAlign';

            scope.IsEdit = true;
            scope.IsDisplay = true;            
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '100px';
            scope.DivWidth;
            scope.IsTitleClick = false;            
            scope.IsFilter = true;
            scope.IsOrder = true;
            scope.IsControlDisplay = false;
            scope.Element;
            scope.Columns = [];

            scope.BindKeyField = attrs["bindkeyfield"].trim();
            scope.BindValueField = attrs["bindvaluefield"].trim();
            scope.BindTextField = attrs["bindtextfield"].trim();

            if (attrs["keyfield"] != undefined && attrs["keyfield"].trim() != "") {
                scope.KeyField = attrs["keyfield"].trim();
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["textfield"] != undefined && attrs["textfield"].trim() != "") {
                scope.TextField = attrs["textfield"].trim();
            }
            if (attrs["entityname"] != undefined && attrs["entityname"].trim() != "") {
                scope.EntityName = attrs["entityname"].trim();
            }
            if (attrs["windowtitle"] != undefined && attrs["windowtitle"].trim() != "") {
                scope.WindowTitle = attrs["windowtitle"].trim();
            }
            if (attrs["isselect"] != undefined && attrs["isselect"].toLocaleLowerCase() == "true") {
                scope.IsSelect = true;
            }

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }
            if (attrs["condition"] != undefined && attrs["condition"].trim() != "") {
                scope.QueryParameter.Condition = attrs["condition"].trim();
            }
            if (attrs["orderby"] != undefined && attrs["orderby"].trim() != "") {
                scope.QueryParameter.OrderBy = attrs["orderby"].trim();
            }
            if (attrs["populate"] != undefined && attrs["populate"].trim() != "") {
                scope.QueryParameter.Populate = attrs["populate"].trim();
            }

            scope.titleClick = function(){
                scope.titleclick();
            };
            scope.filterClick = function(){
                alert('filterClick');
            };
            scope.order = function(){
                dataGridCtrl.scope.loadByOrder(scope, element[0].children[1].children[2]);
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(refRecords){
                //这个判断是为了处理修改编码回车的问题，因为请求后台调用会触发作用域的广播，会导致重复广播报错，所以用值传递来解决
                if(refRecords.length > 0){
                    var refRecord = refRecords[0];
                    if(scope.BindKeyField.indexOf(".") > -1){
                        var fields = scope.BindKeyField.split(".");
                        var strEvalField = "refRecord";
                        //补齐父对象，不然会报父对象undefined
                        for(var i=0; i<fields.length - 1; i++){
                            strEvalField += "." + fields[i];
                            var parentObj = eval(strEvalField);
                            if(parentObj == undefined || parentObj == null){
                                eval(strEvalField + " = {};");
                            }
                        }
                    }
                    if(scope.BindValueField.indexOf(".") > -1){
                        var fields = scope.BindValueField.split(".");
                        var strEvalField = "record";
                        //补齐父对象，不然会报父对象undefined
                        for(var i=0; i<fields.length - 1; i++){
                            strEvalField += "." + fields[i];
                            var parentObj = eval(strEvalField);
                            if(parentObj == undefined || parentObj == null){
                                eval(strEvalField + " = {};");
                            }
                        }
                    }
                    if(scope.BindTextField.indexOf(".") > -1){
                        var fields = scope.BindTextField.split(".");
                        var strEvalField = "record";
                        //补齐父对象，不然会报父对象undefined
                        for(var i=0; i<fields.length - 1; i++){
                            strEvalField += "." + fields[i];
                            var parentObj = eval(strEvalField);
                            if(parentObj == undefined || parentObj == null){
                                eval(strEvalField + " = {};");
                            }
                        }
                    }
                    scope.key = eval("refRecord." + scope.BindKeyField);
                    scope.value = eval("refRecord." + scope.BindValueField);
                    scope.text = eval("refRecord." + scope.BindTextField);
                }
                else{
                    scope.key = null;
                    scope.value = '';
                    scope.text = '';
                }

                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") > -1){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = {
                    Key: eval("record." + scope.KeyField),
                    Value: eval("record." + scope.ValueField),
                    Text: eval("record." + scope.TextField)
                };
                if(oldValue !== scope.key) {
                    if(scope.key == null){
                        eval("record." + scope.KeyField + " = null");
                    }
                    else{
                        eval("record." + scope.KeyField + " = '" + scope.key + "'");
                    }
                    eval("record." + scope.ValueField + " = '" + scope.value + "'");
                    eval("record." + scope.TextField + " = '" + scope.text + "'");
                    dataGridCtrl.scope.cellvaluechange(
                        {
                            columnName: scope.ValueField,
                            newValue: refRecords,
                            oldValue: oldValue
                        }
                    );
                    dataGridCtrl.scope.$digest();
                }
            };
            scope.blur = function(){
                // if(element[0].children[0].children.length == 0){
                    var tdElement = scope.Element.parentNode;
                    element[0].children[0].appendChild(scope.Element);
                    if(scope.key != undefined && scope.key != null && scope.key != '') {
                        tdElement.children[0].innerText = scope.text;
                        tdElement.children[0].setAttribute("title", scope.text);
                    }
                    else{
                        tdElement.children[0].innerHTML = '&nbsp;';
                        tdElement.children[0].removeAttribute("title");
                    }
                    tdElement.children[0].style.display = '';
                // }
            };
            scope.beforeShow = function(refScope){
                scope.beforeshow({refScope: refScope});
            };

            var refDivElement = element[0].children[0];
            var referHtml = '<Refer class="GridBaseControl" beforeshow="beforeShow(refScope)" Condition="' + scope.QueryParameter.Condition + '" OrderBy="' + scope.QueryParameter.OrderBy + '" Populate="' + scope.QueryParameter.Populate + '"';
            referHtml += ' change="change(records)" blur="blur()" keydown="keyDown()" key="key" value="value" text="text"';
            referHtml += ' keyfield="' + scope.BindKeyField + '" valuefield="' + scope.BindValueField + '" textfield="' + scope.BindTextField + '"';
            referHtml += ' entityname="' + scope.EntityName + '" windowtitle="' + scope.WindowTitle + '" ';
            referHtml += 'isselect="' + scope.IsSelect + '" isempty="' + scope.IsEmpty.toString() + '" isgrid="true">';
            for(var i=0; i<refDivElement.children.length; i++){
                var column = {};
                var columnDom = refDivElement.children[i];
                var columnHtml = '<Column'
                if (columnDom.getAttribute("type") != undefined && columnDom.getAttribute("type").trim() != "") {
                    columnHtml += ' type="' + columnDom.getAttribute("type").trim() + '"';
                    column.Type = columnDom.getAttribute("type").trim();
                }
                if (columnDom.getAttribute("displayname") != undefined && columnDom.getAttribute("displayname").trim() != "") {
                    columnHtml += ' displayname="' + columnDom.getAttribute("displayname").trim() + '"';
                    column.DisplayName = columnDom.getAttribute("displayname").trim();
                }
                if (columnDom.getAttribute("width") != undefined && columnDom.getAttribute("width").trim() != "") {
                    columnHtml += ' width="' + columnDom.getAttribute("width").trim() + '"';
                    column.Width = columnDom.getAttribute("width").trim();
                }
                if (columnDom.getAttribute("valuefield") != undefined && columnDom.getAttribute("valuefield").trim() != "") {
                    columnHtml += ' valuefield="' + columnDom.getAttribute("valuefield").trim() + '"';
                    column.ValueField = columnDom.getAttribute("valuefield").trim();
                }
                if (columnDom.getAttribute("enum") != undefined && columnDom.getAttribute("enum").trim() != "") {
                    columnHtml += ' enum="' + columnDom.getAttribute("enum").trim() + '"';
                    column.Enum = columnDom.getAttribute("enum").trim();
                }
                if (columnDom.getAttribute("round") != undefined && columnDom.getAttribute("round").trim() != "") {
                    columnHtml += ' round="' + columnDom.getAttribute("round").trim() + '"';
                    column.Round = columnDom.getAttribute("round").trim();
                }
                if (columnDom.getAttribute("calendartype") != undefined && columnDom.getAttribute("calendartype").trim() != "") {
                    columnHtml += ' calendartype="' + columnDom.getAttribute("calendartype").trim() + '"';
                    column.CalendarType = columnDom.getAttribute("calendartype").trim();
                }
                columnHtml += '></Column>';
                scope.Columns.push(column);

                referHtml += columnHtml;                
            }
            referHtml += '</Refer>';

            $compile(referHtml)(scope, function (clone, scope) {
                    refDivElement.innerHTML = '';
                    refDivElement.appendChild(clone[0]);
                    dataGridCtrl.scope.addColumn(scope, refDivElement);
                }
            );

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}]);

app.directive("dropdownlistcolumn", ['PublicEnum', function(PublicEnum) {
    return {
        require: '^datagrid',
        restrict: "E",
        scope: {
            enum: '=?',
            titleclick: '&'
        },
        template:
            '<td ng-show="IsDisplay">' +
                '<div style="display: none">' +
                    '<DropDownList class="GridBaseControl" style="height:100%;" value="value" change="change()" blur="blur()" keydown="keyDown()" enum="enum" isempty="{{scope.IsEmpty.toString()}}"></DropDownList>' + 
                '</div>' +
                '<!--支持列头点击事件-->' +
                '<div style="width: {{DivWidth}}" ng-if="IsTitleClick" ng-click="order()">' +
                    '<u style="cursor: pointer;" ng-click="titleClick()">{{DisplayName}}</u>' +
                    '<i ng-if="IsOrder">&nbsp;</i>' +
                    '<span ng-if="IsOrder" class="glyphicon glyphicon-menu-down"/>' +
                '</div>' +
                '<!--不支持列头点击事件-->' +
                '<div style="width: {{DivWidth}}" ng-if="!IsTitleClick" ng-click="order()">' +
                    '<span>{{DisplayName}}</span>' +
                    '<i ng-if="IsOrder">&nbsp;</i>' +
                    '<span ng-if="IsOrder" class=""/>' +
                '</div>' +
            '</td>',
        replace: true,
        transclude: true,
        link: function(scope, element, attrs, dataGridCtrl) {
            scope.value;
            scope.IsEdit = true;
            scope.IsDisplay = true;
            scope.ControlType = PublicEnum.ControlType.DropDownList;
            scope.TextAlignClass = 'TextLeftAlign';
            scope.IsEmpty = true;
            scope.DisplayName = 'XXX';
            scope.Width = '80px';
            scope.DivWidth;
            scope.IsTitleClick = false;
            scope.ValueField = '_id';     //绑定字段值，通用
            scope.IsFilter = true;
            scope.IsOrder = true;

            if (attrs["displayname"] != undefined && attrs["displayname"].trim() != "") {
                scope.DisplayName = attrs["displayname"].trim();
            }
            if (attrs["width"] != undefined && attrs["width"].trim() != "") {
                scope.Width = attrs["width"].trim();
                element[0].removeAttribute("width");
            }
            if (attrs["valuefield"] != undefined && attrs["valuefield"].trim() != "") {
                scope.ValueField = attrs["valuefield"].trim();
            }
            if (attrs["isempty"] != undefined && attrs["isempty"].trim().toLocaleLowerCase() == "false") {
                scope.IsEmpty = false;
            }
            if (attrs["istitleclick"] != undefined && attrs["istitleclick"].trim().toLocaleLowerCase() == "true") {
                scope.IsTitleClick = true;
            }
            if (attrs["isfilter"] != undefined && attrs["isfilter"].trim().toLocaleLowerCase() == "false") {
                scope.IsFilter = false;
            }
            if (attrs["isorder"] != undefined && attrs["isorder"].trim().toLocaleLowerCase() == "false") {
                scope.IsOrder = false;
            }

            dataGridCtrl.scope.addColumn(scope, element[0].children[0]);

            scope.titleClick = function(){
                scope.titleclick();
            };
            scope.filterClick = function(){
                alert('filterClick');
            };
            scope.order = function(){
                dataGridCtrl.scope.loadByOrder(scope, element[0].children[1].children[2]);
            };

            scope.keyDown = function(){
                dataGridCtrl.scope.keyDown();
                if(event.keyCode == 13 || event.keyCode == 38 || event.keyCode == 40) {
                    event.preventDefault();
                }
            };
            scope.change = function(){
                var record = dataGridCtrl.scope.module.FocusedRecord;
                if(scope.ValueField.indexOf(".") > -1){
                    var fields = scope.ValueField.split(".");
                    var strEvalField = "record";
                    //补齐父对象，不然会报父对象undefined
                    for(var i=0; i<fields.length - 1; i++){
                        strEvalField += "." + fields[i];
                        var parentObj = eval(strEvalField);
                        if(parentObj == undefined || parentObj == null){
                            eval(strEvalField + " = {};");
                        }
                    }
                }

                var oldValue = eval("record." + scope.ValueField);
                if(oldValue !== scope.value) {
                    eval("record." + scope.ValueField + " = " + scope.value.toString());
                    dataGridCtrl.scope.cellvaluechange(
                        {
                            columnName: scope.ValueField,
                            newValue: scope.value,
                            oldValue: oldValue
                        }
                    );
                    dataGridCtrl.scope.$digest();
                }
            };
            scope.blur = function(){
                var td = event.srcElement.parentNode;
                element[0].children[0].appendChild(event.srcElement);
                if(scope.value != undefined && scope.value !== "" && scope.value > -1) {
                    var isFind = false;
                    for(var option in scope.enum){
                        if(scope.enum[option].Value == scope.value){
                            isFind = true;
                            td.children[0].innerText = scope.enum[option].Text;
                            td.children[0].setAttribute("title", scope.enum[option].Text);
                            break;
                        }                                
                    }
                    if(!isFind){
                        td.children[0].innerHTML = '&nbsp;';
                        td.children[0].removeAttribute("title");
                    }
                }
                else{
                    td.children[0].innerHTML = '&nbsp;';
                }
                td.children[0].style.display = '';
            };

            element[0].children[0].addEventListener('keydown',
                scope.keyDown,
                false
            );

            scope.$watch(
                function(){
                    return scope.Width;
                },
                function(){
                    scope.DivWidth = (Number(scope.Width.replace('px', '')) - 4).toString() + 'px';
                }
            );
            scope.$watch(
                function(){
                    return attrs["isedit"];
                },
                function(){
                    if(attrs["isedit"] != undefined && attrs["isedit"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsEdit = false;
                    }
                    else{
                        scope.IsEdit = true;
                    }
                }
            );
            scope.$watch(
                function(){
                    return attrs["isdisplay"];
                },
                function(){
                    if(attrs["isdisplay"] != undefined && attrs["isdisplay"].trim().toLocaleLowerCase() == 'false'){
                        scope.IsDisplay = false;
                    }
                    else{
                        scope.IsDisplay = true;
                    }
                }
            );
        }
    }
}]);

// app.directive('onDataGridBodyLoaded', function ($timeout) {
//     return {
//         restrict: 'A',
//         link: function(scope, element, attr) {
//             if (scope.$last === true) {
//                 $timeout(function() {
//                     scope.$emit('$DataGridBodyLoaded');
//                 });
//             }
//         }
//     };
// });

// app.directive('onDataGridRightLoaded', function ($timeout) {
//     return {
//         restrict: 'A',
//         link: function(scope, element, attr) {
//             if (scope.$last === true) {
//                 $timeout(function() {
//                     scope.$emit('$DataGridRightLoaded');
//                 });
//             }
//         }
//     };
// });
